<template>
  <div>
    <el-checkbox-group
      v-model="value"
      :size="setting.size"
      :min="setting.checkLimit?.minSelect"
      :max="setting.checkLimit?.maxSelect"
      :disabled="props.disabled"
    >
      <el-checkbox
        v-for="(option, index) in setting.default"
        :key="index"
        :value="option.label || option.placeholder"
        :label="option.label || option.placeholder"
      />
    </el-checkbox-group>
  </div>
</template>

<script setup>
import { computed, onMounted } from 'vue'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  setting: {
    type: Object,
    default: () => {}
  },
  formRules: {
    type: Object,
    default: () => ({})
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:modelValue', 'update:formRules'])

const value = computed({
  get: () => props.modelValue,
  set: (val) => {
    emits('update:modelValue', val)
  }
})

const formRules = computed({
  get: () => props.formRules,
  set: (val) => {
    emits('update:formRules', val)
  }
})

// 生成校验规则
const generateRules = () => {
  const rules = []

  if (props.setting.require) {
    rules.push({
      required: true,
      message: '此题为必填题',
      trigger: 'change'
    })
  }

  // 选项数量限制校验
  const { minSelect, maxSelect } = props.setting
  if (minSelect && maxSelect) {
    rules.push({
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          if (!props.setting.require) {
            callback()
            return
          }
        }
        if (value.length < minSelect) {
          callback(new Error(`至少选择${minSelect}项`))
          return
        }
        if (value.length > maxSelect) {
          callback(new Error(`最多选择${maxSelect}项`))
          return
        }
        callback()
      },
      trigger: 'change'
    })
  }

  formRules.value[props.setting.formItemId] = rules
}

// 组件挂载时生成验证规则
onMounted(() => {
  generateRules()
})
</script>

<style lang="scss" scoped>
:deep(.el-checkbox-group) {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;

  .el-checkbox {
    margin-right: 0;
    padding: 4px 0;
    border-radius: 4px;
    height: auto;

    &:hover {
      background-color: #f5f7fa;
    }
  }
}
</style>
